import React, { useRef, useEffect, useState } from 'react';
import '@alifd/next/dist/next.css';
import { Button, Input, Range } from '@alifd/next';
import "./index.less";

import PauseImg from './assets/pause.png';
import PlayImg from './assets/play.png';

const VideoCanvas = ({ videos }) => {
  function onChange(value) {
    console.log(value);
  }
  function formatDuration(totalSeconds) {
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = Math.floor(totalSeconds % 60);

    const formattedHours = hours.toString().padStart(2, '0');
    const formattedMinutes = minutes.toString().padStart(2, '0');
    const formattedSeconds = seconds.toString().padStart(2, '0');

    return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
  }
  const nowDuration = '00:00:00'
  const total = (videos.reduce((acc, scene) => {
    const duration = scene.videoEndTime - scene.videoStartTime;
    return acc + duration;
  }, 0))
  // console.log(total);
  const totalDuration = formatDuration(total.toFixed(3));
  console.log(totalDuration);
  // 定义当前播放视频的索引
  const [currentVideoIndex, setCurrentVideoIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false); // 添加状态来控制播放状态
  const [allVideosEnded, setAllVideosEnded] = useState(false); // 添加状态来标记所有视频是否播放完毕
  const canvasRef = useRef(null);
  const videosRef = useRef([]);
  //切换播放暂停
  const togglePlay = () => {
    console.log( videosRef.current[currentVideoIndex]);
    if (isPlaying) {
      videosRef.current[currentVideoIndex].pause();
    } else {
      videosRef.current[currentVideoIndex].play()
      // console.log(index);
      // video.play();
    }
    setIsPlaying(!isPlaying);
  };

  
  useEffect(() => {

    // 每次渲染后都会执行此处的代码
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');

    const renderVideos = () => {
      videosRef.current.forEach(video => {
        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 绘制视频帧
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      });
    };

    const loadVideos = () => {
      videosRef.current = videos.map((videoData, index) => {
        const video = document.createElement('video');
        video.src = videoData.videoUrl;
        // video.muted = true; // 静音播放
        video.autoplay = false; // 设置或返回是否在就绪（加载完成）后随即播放视频。
        // video.preload = 'auto';
        video.currentTime = videoData.videoStartTime;
        video.addEventListener('loadedmetadata', () => {
          video.currentTime = videoData.videoStartTime;
        });
        video.addEventListener('ended', () => {
          console.log('当前视频播放结束' + index);
          const allEnded = videosRef.current.every(video => video.ended);
          if (allEnded) {
            setAllVideosEnded(true); // 所有视频都已播放完毕
          }
        });
        return video;
      });
      console.log(loadVideos);
    };

    const playVideos = () => {
      videosRef.current.forEach(video => {
        video.play();
      });
    };

    loadVideos();
    // playVideos();

    // 绘制视频帧
    const renderFrame = () => {
      // console.log('绘制视频帧');
      renderVideos();
      requestAnimationFrame(renderFrame);
    };
    renderFrame();

    return () => {
      videosRef.current.forEach(video => {
        video.pause();
        video.src = '';
        video.load();
      });
    };
  }, [videos]);



  // useEffect(() => {
  //   if (allVideosEnded) {
  //     console.log('所有视频镜头播放完毕');
  //     setIsPlaying(false)
  //   }
  // }, [allVideosEnded]);
  return (<div className="videoWrap">
    <canvas ref={canvasRef} width={295} height={500} />
    <div className="controls">

      <Range slider={'single'} defaultValue={0} max={total} onChange={onChange} />
      <div className="controlBtns">
        <div className="paly_btn" onClick={togglePlay}>
          <img src={`${isPlaying ? PlayImg : PauseImg}`} />
        </div>
        <span className="times">
          {nowDuration}/{totalDuration}
        </span>
      </div>
    </div>
  </div>)

};

export default VideoCanvas;